﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using CrypHelper;
using S7PlcHelper;
using ORM;
using System.Threading;

namespace OpcSelfHost.basePage
{
    public static class CommonBase
    {
        /// <summary>
        /// opc 服务ip，默认当前服务器
        /// </summary>
        public static string serverip { get; set; }

        public static List<PlcConfig> mPlcConfigs { get; set; }

        public static ConfigModel Dbconfig { get; set; }

        /// <summary>
        /// opc服务名称
        /// </summary>
        public static string servername { get; set; }

        /// <summary>
        /// 数据库连接是否检查
        /// </summary>
        public static bool isDbChecked = false;


        /// <summary>
        /// plc数据采集任务管理
        /// </summary>
        /// 
        public static List<CancellationTokenSource> dic_tokenSource = new List<CancellationTokenSource>();
        public static List<CancellationToken> dic_token = new List<CancellationToken>();


        /// <summary>
        /// plc转发任务管理
        /// </summary>
        /// 
        public static List<CancellationTokenSource> dic_tokenSource_plcsend = new List<CancellationTokenSource>();
        public static List<CancellationToken> dic_token_plcsend = new List<CancellationToken>();

        /// <summary>
        /// 获取当前目录
        /// </summary>
        /// <returns></returns>
        public static string CurrentDirectory()
        {
            return Environment.CurrentDirectory;
        }

        /// <summary>
        /// ajax传入json格式字符串转obj
        /// </summary>
        /// <param name="ajaxdata"></param>
        /// <returns></returns>
        public static dynamic Json2Obj(JObject ajaxdata)
        {
            dynamic jsonStr = JsonConvert.SerializeObject(ajaxdata);
            dynamic jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);
            return jsonParams;
        }



        /// <summary>
        /// 返回授权数
        /// </summary>
        /// <param name="machinecode">机器码</param>
        /// <param name="license">license</param>
        /// <returns>返回授权数</returns>
        public static int LicenseValition(string machinecode,string license)
        {
            int licenseNUM = 0;
            if (license == "test" || license == "haitai")
            {
                return 1;
            }
            DiyCrypto DiyCryptoClass = new DiyCrypto();
            string lincenseOK  =  DiyCryptoClass.Decrypto(license);
          
            try
            {

                string ReadMachine = lincenseOK.Substring(0, lincenseOK.Length-4);
                string Readnums_str = lincenseOK.Substring(lincenseOK.Length - 4, 4);
         

            if (ReadMachine== machinecode)
            { 
                     
                    //创建授权文件 
                    licenseNUM = int.Parse(Readnums_str);
                    string dir = Environment.CurrentDirectory + "\\data\\";
                    string path = dir + "license";
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite); 
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(license);
                    sw.Flush();
                    sw.Close();


                }
            else
            {
                licenseNUM = 0;

            }


            }
            catch (Exception)
            {

                licenseNUM = 0;
            }


            return licenseNUM;
        }

     


        /// <summary>  
        /// 写入值  
        /// </summary>  
        /// <param name="key"></param>  
        /// <param name="value"></param>  
        public static void ConfigSetValue(string key, string value)
        {
            //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>  
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件   
        }

        /// <summary>  
        /// 读取指定key的值  
        /// </summary>  
        /// <param name="key"></param>  
        /// <returns></returns>  
        public static string ConfigGetValue(string key)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
                return "";
            else
                return config.AppSettings.Settings[key].Value;
        }

         


    }
}
